import pandas as pd
import os
import json

def handle_inclusion_relationship(df):
    included_data = []

    def merge_kline(kline1, kline2, direction):
        if direction == 'up':
            return {
                'timestamp': kline1['timestamp'],
                'high': max(kline1['high'], kline2['high']),
                'low': max(kline1['low'], kline2['low']),
                'volume': kline1['volume'] + kline2['volume'],
                'top_fractal': False,
                'bottom_fractal': False
            }
        elif direction == 'down':
            return {
                'timestamp': kline1['timestamp'],
                'high': min(kline1['high'], kline2['high']),
                'low': min(kline1['low'], kline2['low']),
                'volume': kline1['volume'] + kline2['volume'],
                'top_fractal': False,
                'bottom_fractal': False
            }

    i = 0
    while i < len(df):
        current = df.iloc[i].to_dict()
        current['top_fractal'] = False
        current['bottom_fractal'] = False
        if len(included_data) == 0:
            included_data.append(current)
        else:
            previous = included_data[-1]
            if current['high'] <= previous['high'] and current['low'] >= previous['low']:
                included_data[-1] = merge_kline(previous, current, 'up')
            elif current['high'] >= previous['high'] and current['low'] <= previous['low']:
                included_data[-1] = merge_kline(previous, current, 'down')
            else:
                included_data.append(current)
        i += 1

    return pd.DataFrame(included_data)

def process_inclusion_recursive(df):
    previous_length = 0
    while previous_length != len(df):
        previous_length = len(df)
        df = handle_inclusion_relationship(df)
    return df

if __name__ == '__main__':
    try:
        df = pd.read_csv('../static/bnb_usdt_klines.csv')
        print("成功读取 bnb_usdt_klines.csv 文件")
    except Exception as e:
        print(f"读取 bnb_usdt_klines.csv 文件失败: {e}")
        raise

    try:
        included_data = process_inclusion_recursive(df)
        print("成功处理包含关系")
    except Exception as e:
        print(f"处理包含关系失败: {e}")
        raise

    try:
        os.makedirs('../static', exist_ok=True)
        print("确保 static 目录存在")
    except Exception as e:
        print(f"创建 static 目录失败: {e}")
        raise

    try:
        with open('../static/included_bnb_usdt_klines.json', 'w') as f:
            included_data.to_json(f, orient='records', indent=4)
        print("包含关系数据已保存到 static/included_bnb_usdt_klines.json")
    except Exception as e:
        print(f"保存包含关系数据失败: {e}")
        raise
